package com.BaoHua.demo.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.BaoHua.demo.bean.RequestTest;
import com.BaoHua.demo.bean.Test;
import com.BaoHua.demo.mapper.TestMapper;
import com.BaoHua.demo.utils.ErrorUtils;
import com.BaoHua.demo.utils.Groups;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Controller
public class IndexController {

	@Autowired
	HttpServletRequest request;
	
	@Autowired
	private TestMapper mapper;
	
	@RequestMapping({"/","/index"})
	public String index() {
		return "index";
	}
	
	
	@RequestMapping("/page")
	@ResponseBody
	public PageInfo<Test> page(@RequestParam(name="id", defaultValue="1")int currentPage,@RequestParam(name="num", defaultValue="10")int pageNum) {
		PageHelper.startPage(currentPage,pageNum);
		List<Test> one = mapper.getList();
		//设置分页
		PageInfo<Test> info = new PageInfo<Test>(one);
		return info;
	}
	
	
	@RequestMapping("/test")
	@ResponseBody
	public Map<String,Object> Test(@Validated(value = {Groups.Default.class,Groups.Update.class})RequestTest test, BindingResult bindingResult) {
		Map<String,Object> map = new HashMap<String,Object>();
		List<ErrorUtils> errors = new ArrayList<ErrorUtils>();
		if(bindingResult.hasErrors()){
			for (FieldError fieldError : bindingResult.getFieldErrors()) {
				errors.add(new ErrorUtils(fieldError.getField(), fieldError.getDefaultMessage()));
			}
			map.put("info", errors);
			map.put("code", 500);
			return map;
		}
		return map;
	}
	
}
